package com.ys.store.service.impl;

import com.ys.store.entity.User;
import com.ys.store.mapper.UserMapper;
import com.ys.store.service.IUserService;
import com.ys.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;


@Service   //将当前类产生的对象交给spring管理，自动创建对象
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /*用户注册*/
    @Override
    public void reg(User user) {
        //通过user参数获取username
        String username = user.getUsername();
        // 调用findByUsername(username)判断是否注册过
        User result =  userMapper.findByUsername(username);
        //判断是否为null，不是则抛出用户名被占用异常
        if(result != null){
            throw new UsernameDuplicatedException("用户名被占用");
        }

        // 密码加密处理的实现：md5算法的形式：类似于g9grgh8r9-gg8fefrfh99-ghhrfgwse88这样的
        // （串 + password + 串），传给md5算法加密，连续加密三次
        // 串：盐值，本身也是一个随机的字符串
        String oldPassword = user.getPassword();
        // 获取盐值，随机生成
        String salt = UUID.randomUUID().toString().toUpperCase();
        // 补全盐值
        user.setSalt(salt);
        // 加密处理
        String md5Password = getMD5Password(oldPassword, salt);
        // 重新补全入user对象
        user.setPassword(md5Password);



        // 补全数据
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        Date data = new Date();
        user.setCreatedTime(data);
        user.setModifiedTime(data);

        //执行注册业务的功能实现
        Integer rows = userMapper.insert(user);
        if(rows != 1){
            throw new InsertException("在注册时发生了其他异常");
        }

    }

    @Override
    public User login(String username, String password) {
        User result = userMapper.findByUsername(username);
        if(result == null){
            throw new UserNotFoundException("用户数据不存在");
        }
        // 判断是否注销
        if(result.getIsDelete().equals(1)){
            throw new UserNotFoundException("该用户已注销");
        }

        // 判断密码是否相等
        String oldPassword =result.getPassword();
        String salt = result.getSalt();
        String newMD5Password = getMD5Password(password,salt);

        if (!oldPassword.equals(newMD5Password)){
            throw new PasswordNotMatchException("密码错误");
        }

        // 新建一个user为后面页面间数据传递做筛选,多余的数据不传递
        User user = new User();
        user.setUsername(result.getUsername());
        user.setUid(result.getUid());
        user.setAvatar(result.getAvatar());

        return user;
    }

    @Override
    public void ChangePassword(Integer uid, String username, String oldPassword, String newPassword) {
       User result =  userMapper.findByUid(uid);
       if(result == null || result.getIsDelete() == 1){
           throw new UserNotFoundException("用户数据不存在");
       }
        String oldMD5Password = getMD5Password(oldPassword ,result.getSalt());
       // 判断用户旧密码是否正确
       if(!result.getPassword().equals(oldMD5Password)){
           throw new PasswordNotMatchException("密码错误");
       }
       // 设置新密码
        String newMD5Password = getMD5Password(newPassword ,result.getSalt());
        Integer rows =  userMapper.updatePasswordByUid(uid,newMD5Password,username,new Date());
        if(rows != 1){
            throw new UpdateException("更新数据时异常");
        }

    }


    /*定义一个md5加密处理*/
    private String getMD5Password(String password,String salt){
        //md5加密方法调用,三次
        for(int i = 0 ; i < 3; i++){
          password =  DigestUtils.md5DigestAsHex((salt + password +salt).getBytes()).toUpperCase();
        }
        return password;
    }

}
